<template>
  <el-container height='100%'>
    <el-aside width='380px' height='100%' style="margin-bottom:0">
      <el-row type="flex" justify="space-around">
        <el-col :span="11">
          <el-input v-model="projectListQuery.param.name" placeholder="请输入工程名称" size="small" />
        </el-col>
        <el-col :span="7">
          <el-button-group>
            <el-button type="primary" size="small" icon="el-icon-search" @click="ProjectHandleFilter" />
            <el-button v-if="add_project_button_status" size="small" icon="el-icon-plus" @click="ProjectHandleAdd" />
          </el-button-group>
        </el-col>
        <el-col :span="4">
          <el-upload v-if="upload_excel_project_button_status" action="" :show-file-list="false" single :http-request="upload_excel" :before-upload="before_upload_excel" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
            <el-button size="small" type="primary">导入</el-button>
          </el-upload>
        </el-col>
      </el-row>
      <el-table ref="projectLists" class="project-table" :data="projectLists" :show-header="false" @row-click="ProjectClick" highlight-current-row>
        <el-table-column>
          <template slot-scope="scope">
            <div>
              <p><b>{{scope.row.projectName}}</b></p>
              <div><span>{{scope.row.projectDesc}}</span></div>
              <el-button-group>
                <el-button v-if="upd_project_button_status" :disabled="scope.row.state!==0" type="primary" icon="el-icon-edit" size='mini' @click="ProjectHandleEdit(scope.row)"></el-button>
                <el-button v-if="finish_project_button_status" :disabled="scope.row.state!==0" type="success" icon="el-icon-finished" size='mini' @click="ProjectHandleFinish(scope.row.id)"></el-button>
                <!-- <el-button :disabled="scope.row.state!==0" type="danger" icon="el-icon-delete" size='mini' @click="ProjectHandleDelete(scope.row.id)"></el-button> -->
              </el-button-group>
              <el-tag v-if="scope.row.state===0" class="tag-right" type="" size="medium">进行中</el-tag>
              <el-tag v-else class="tag-right" type="success" size="medium">已完成</el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table><!-- :hide-on-single-page='true'  -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="pager" small background :current-page.sync="projectListQuery.page" :page-size="projectListQuery.size" :total="totalProject" :pager-count="5"></el-pagination>
    </el-aside>

    <el-main>
      <el-tabs v-model="activeName" width="100%" @tab-click="handleTabsClick">
        <el-tab-pane label="项目管理" name="ProjectItem" width="100%">
          <project-item-page ref="ProjectItem" :ProjectId='projectId' width="100%"></project-item-page>
        </el-tab-pane>
        <el-tab-pane label="人员管理" name="ProjectUser">
          <project-user-page ref="ProjectUser" :ProjectId='projectId' width="100%"></project-user-page>
        </el-tab-pane>
        <el-tab-pane label="单据管理" name="ProjectBill">
          <project-bill-page ref="ProjectBill" :ProjectId='projectId' width="100%"></project-bill-page>
        </el-tab-pane>
        <el-tab-pane label="预决算管理" name="ProjectPreFinalAccountFile">
          <project-pre-final-account-file-page ref="ProjectPreFinalAccountFile" :ProjectId='projectId' width="100%"></project-pre-final-account-file-page>
        </el-tab-pane>
      </el-tabs>
    </el-main>

    <el-dialog :title="projectTextMap[projectDialogStatus]" :visible.sync="projectDialogFormVisible" :before-close="CloseProjectDialog" :close-on-click-modal="false" width="45%">

      <el-form :model="projectForm" :rules="projectFromRules" ref="projectForm" label-width="150px">
        <el-form-item v-show="false" label="Id" prop="id">
          <el-input v-model="projectForm.id" />
        </el-form-item>
        <el-form-item label="工程名称" prop="projectName">
          <el-input v-model="projectForm.projectName" />
        </el-form-item>
        <el-form-item label="工程描述" prop="projectDesc">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="projectForm.projectDesc" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button @click="ProjectHandleCancel()">
          取 消
        </el-button>
        <el-button v-if="projectDialogStatus=='create'" type="primary" @click="ProjectHandleCreate()">
          确 定
        </el-button>
        <el-button v-if="projectDialogStatus=='update'" type="primary" @click="ProjectHandleUpdate()">
          确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="导入excel" :visible.sync="projectUploadDialogFormVisible" :before-close="projectUploadHandleCancel" :close-on-click-modal="false" width="80%">
      <el-tag type="warning" style="margin-left: 10px; margin-bottom: 20px">工程名称：</el-tag>
      <el-input style="width: 400px; margin-left: 10px; margin-bottom: 20px" v-model="uploadData.ProjectName" />
      <el-button type="primary" @click="projectUploadHandleSave" style="float: right">
        保存
      </el-button>
      <el-table :data="uploadData.Datas" style="width: 100%;" max-height="900">
        <el-table-column width="50" label="序号" fixed="left">
          <template slot-scope="scope">
            {{scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column v-for="uheader in uploadHeader" :key="uheader.label" width="200px">
          <template slot-scope="scope" slot="header">
            <el-tag class="upload-table-header-tab">{{uheader.lable}}</el-tag>
            <el-select size='mini' v-model="uheader.jsonName" :placeholder="'请选择'+uheader.label">
              <el-option v-for="header in uploadData.Header" :key="header.ChineseName" :label="header.ChineseName" :value="header.DataKey">
              </el-option>
            </el-select>
          </template>
          <template slot-scope="scope">
            <el-input size='mini' :autosize="{ maxRows: 1}" v-if="scope.row.hasOwnProperty(uheader.jsonName)" :type="uheader.type" v-model="scope.row[uheader.jsonName]" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="danger" size='mini' @click="ProjectUploadHandleDelete(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button @click="projectUploadHandleCancel">
          取 消
        </el-button>
      </div> -->
    </el-dialog>
  </el-container>
</template>
<script>

import { mapGetters } from 'vuex';
import { getProjectInfo, addProjectInfo, modifyProjectInfo, delProjectInfo, finishProject, uploadExcelFile, uploadExcelDataSeve } from '@/api/projectInfo'
import ProjectItemPage from './ProjectItem'
import ProjectUserPage from './ProjectUser'
import ProjectBillPage from './ProjectBill'
import ProjectPreFinalAccountFilePage from './ProjectPreFinalAccountFile'
// import ProjectCostPage from './ProjectCost'
export default {
  name: 'projectInfo',
  components: {
    ProjectItemPage, ProjectUserPage, ProjectBillPage, ProjectPreFinalAccountFilePage //, ProjectCostPage
  },
  data() {
    return {
      tabPages: ["ProjectItem", "ProjectUser", "ProjectBill", "ProjectPreFinalAccountFile"],
      projectDialogStatus: "",
      projectDialogFormVisible: false,
      projectUploadDialogFormVisible: false,
      totalProject: 0,
      projectTextMap: {
        create: "创建",
        update: "修改",
        delete: "删除"
      },
      projectForm: {
        id: 0,
        projectName: undefined,
        projectDesc: undefined
      },
      projectFromRules: {
        projectName: [
          { required: true, message: "请填写工程名称", trigger: "blur" },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        projectDesc: [
          { max: 100, message: '长度大于 100 个字符', trigger: 'blur' }
        ]
      },
      projectListQuery: {
        page: 1,
        size: 25,
        param: {
          name: undefined
        }
      },
      projectLists: [],
      projectId: 0,

      activeName: 'ProjectItem',
      successCode: 20000,

      add_project_button_status: false,
      upd_project_button_status: false,
      finish_project_button_status: false,
      upload_excel_project_button_status: false,

      uploadData: {

      },
      uploadHeader: [{
        lable: "项目单号",
        jsonName: 'ItemNo',
        propName: 'ItemNo',
        type: 'text',
      }, {
        lable: "项目名称",
        jsonName: 'ItemName',
        propName: 'ItemName',
        type: 'text',
      }, {
        lable: "项目描述",
        jsonName: 'ItemDesc',
        propName: 'ItemDesc',
        type: 'textarea',
      }, {
        lable: "预算用量",
        jsonName: 'BudgetDosage',
        propName: 'BudgetDosage',
        type: 'number',
      }, {
        lable: "预算单价",
        jsonName: 'BudgetAmount',
        propName: 'BudgetAmount',
        type: 'number',
      }, {
        lable: "实际用量",
        jsonName: 'FactDosage',
        propName: 'FactDosage',
        type: 'number',
      }, {
        lable: "实际单价",
        jsonName: 'FactAmount',
        propName: 'FactAmount',
        type: 'number',
      }, {
        lable: "单位",
        jsonName: 'ItemUnit',
        propName: 'ItemUnit',
        type: 'text',
      }],
    }
  },
  computed: {
    ...mapGetters(["elements"])
  },
  created() {
    this.getProjectLists();
    if (this.elements['add_project']) {
      this.add_project_button_status = true;
    }
    if (this.elements['upd_project']) {
      this.upd_project_button_status = true;
    }
    if (this.elements['finish_project']) {
      this.finish_project_button_status = true;
    }
    if (this.elements['upload_excel_project']) {
      this.upload_excel_project_button_status = true;
    }
    this.$nextTick(() => {
      this.handleTabsClick();
    });
  },
  methods: {
    // 工程筛选按钮
    ProjectHandleFilter() {
      this.getProjectLists();
    },
    // 工程增加按钮
    ProjectHandleAdd() {
      this.ResetProjectDialog();
      this.projectDialogFormVisible = true;
      this.projectDialogStatus = 'create';
    },
    // 工程提交增加表单
    ProjectHandleCreate() {
      this.$refs['projectForm'].validate(valid => {
        if (!valid) {
          return false;
        }
        addProjectInfo(this.projectForm).then(resp => {
          const code = resp.code;
          const msg = resp.message;
          if (code === this.successCode) {
            this.projectDialogFormVisible = false;
            this.getProjectLists();
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          }
          else {
            this.$notify({
              title: '失败',
              message: mesg,
              type: 'warning',
              duration: 2000
            });
          }
        });
      });
    },
    // 工程修改按钮
    ProjectHandleEdit(row) {
      this.ResetProjectDialog();
      this.projectDialogFormVisible = true;
      this.projectDialogStatus = 'update';
      this.$nextTick(() => {
        this.projectForm = {
          id: row.id,
          projectName: row.projectName,
          projectDesc: row.projectDesc
        };
      });
    },
    // 工程提交修改表单
    ProjectHandleUpdate() {
      this.$refs['projectForm'].validate(valid => {
        if (!valid) {
          return false;
        }
        modifyProjectInfo(this.projectForm).then(resp => {
          const code = resp.code;
          const msg = resp.message;
          if (code === this.successCode) {
            this.projectDialogFormVisible = false;
            this.getProjectLists();
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
              duration: 2000
            });
          }
          else {
            this.$notify({
              title: '失败',
              message: mesg,
              type: 'warning',
              duration: 2000
            });
          }
        });
      })
    },
    // 工程删除按钮
    ProjectHandleDelete(id) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delProjectInfo(id).then(() => {
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
          this.getProjectLists();
        });
      });
    },
    // 标记为完成按钮
    ProjectHandleFinish(id) {
      this.$confirm("此操作将标记为完成, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        finishProject(id).then(() => {
          this.$notify({
            title: "成功",
            message: "操作成功",
            type: "success",
            duration: 2000
          });
          this.getProjectLists();
        });
      });
    },
    // 工程取消按钮
    ProjectHandleCancel() {
      this.ResetProjectDialog();
    },
    // 重置工程弹出框
    ResetProjectDialog() {
      this.projectDialogFormVisible = false;
      this.projectDialogStatus = '';
      if (this.$refs['projectForm']) {
        this.$refs['projectForm'].resetFields();
      }
    },
    CloseProjectDialog() {
      this.ResetProjectDialog();
    },
    getProjectLists() {
      getProjectInfo(this.projectListQuery).then(resp => {
        const code = resp.code;
        const msg = resp.message;
        const datas = resp.datas;
        if (code !== this.successCode) {
          return;
        }
        this.totalProject = datas.total;
        this.projectLists = datas.datas;
        if (this.projectLists[0] && !this.projectId) {
          this.projectId = this.projectLists[0].id;
          this.$nextTick(() => {
            this.$refs["projectLists"].setCurrentRow(this.projectLists[0]);
          });
        }
      });
    },
    handleCurrentChange(val) {
      this.projectListQuery.page = val;
      this.getProjectLists();
    },
    handleSizeChange(val) {
      this.projectListQuery.size = val;
      this.getProjectLists();
    },
    ProjectClick(row, column, event) {
      this.projectId = row.id;
    },
    upload_excel(data) {
      // 数据在data.file
      var loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      uploadExcelFile(data.file).then(resp => {
        var datas = resp.datas[0];
        if (datas) {
          loading.close();
          this.projectUploadDialogFormVisible = true;
          this.uploadData = datas;
          console.log(this.uploadData);
        }
        else {
          this.$notify({
            title: '失败',
            message: "未能解析数据",
            type: 'warning',
            duration: 2000
          });
        }
        // 
      }).catch(() => {
        loading.close();
      })
    },
    before_upload_excel(file) {
      return true;
      // if (file.type === "application/vnd.ms-excel"
      //   || file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
      //   return true;
      // }
      // this.$notify({
      //   title: '失败',
      //   message: "文件格式异常，请上传正确的excel文件",
      //   type: 'warning',
      //   duration: 2000
      // });
      // return false;
    },
    ProjectUploadHandleDelete(index) {
      this.uploadData.Datas.splice(index, 1);
    },
    projectUploadHandleCancel() {
      this.projectUploadDialogFormVisible = false;
      this.uploadData = {};
      this.uploadHeader = [{
        lable: "项目单号",
        jsonName: 'ItemNo',
        propName: 'ItemNo',
        type: 'text',
      }, {
        lable: "项目名称",
        jsonName: 'ItemName',
        propName: 'ItemName',
        type: 'text',
      }, {
        lable: "项目描述",
        jsonName: 'ItemDesc',
        propName: 'ItemDesc',
        type: 'textarea',
      }, {
        lable: "预算用量",
        jsonName: 'BudgetDosage',
        propName: 'BudgetDosage',
        type: 'number',
      }, {
        lable: "预算单价",
        jsonName: 'BudgetAmount',
        propName: 'BudgetAmount',
        type: 'number',
      }, {
        lable: "实际用量",
        jsonName: 'FactDosage',
        propName: 'FactDosage',
        type: 'number',
      }, {
        lable: "实际单价",
        jsonName: 'FactAmount',
        propName: 'FactAmount',
        type: 'number',
      }, {
        lable: "单位",
        jsonName: 'ItemUnit',
        propName: 'ItemUnit',
        type: 'text',
      }]
    },
    projectUploadHandleSave() {
      var sendData = [];
      if (this.uploadData.Datas.length <= 0) {
        this.$notify({
          title: '失败',
          message: "表单中没有数据",
          type: 'warning',
          duration: 2000
        });
        return;
      }
      var firstUploadData = this.uploadData.Datas[0];
      for (let h = 0; h < this.uploadHeader.length; h++) {
        const header = this.uploadHeader[h];
        if (!firstUploadData.hasOwnProperty(header.jsonName)) {
          this.$notify({
            title: '失败',
            message: lable + "列没有数据",
            type: 'warning',
            duration: 2000
          });
          return;
        }
      }
      for (let i = 0; i < this.uploadData.Datas.length; i++) {
        const data = this.uploadData.Datas[i];
        const rData = {};
        for (let h = 0; h < this.uploadHeader.length; h++) {
          const header = this.uploadHeader[h];
          rData[header.propName] = data[header.jsonName]
        }
        sendData.push(rData);
      }
      console.log(sendData);
      uploadExcelDataSeve({ ProjectName: this.uploadData.ProjectName, ItemDatas: sendData }).then(resp => {
        this.$notify({
          title: '成功',
          message: "导入数据成功",
          type: 'success',
          duration: 2000
        });
        this.getProjectLists();
        this.projectUploadHandleCancel();
      });
    },
    handleTabsClick(tab, event) {
      this.tabPages.forEach(x => {
        if (x === this.activeName) {
          this.$refs[x].show();
        } else {
          this.$refs[x].hide();
        }
      })
    }
  }
}
</script>
<style>
.project-table {
  margin: 10px 0;
}
.tag-right {
  position: absolute;
  right: 8px;
  bottom: 8px;
}
.app-main section.el-container {
  width: 100%;
}
.el-table .select-row {
  background: #f0f9eb;
}
.el-table__body tr.current-row > td {
  background-color: rgb(234, 251, 255);
}
.upload-header-tab {
  width: 180px !important;
  margin-left: 10px;
}
.upload-table-header-tab {
  width: 100% !important;
  margin-bottom: 10px;
}
</style>
